﻿using h2sbk_sharp.DoNetExt;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using H2SDB;

namespace h2sbk_sharp.Controllers
{
    public class DataController : ApiController
    {

        private HttpResponseMessage data_import2 (string[] lines)
        {
            string rtv = null;
            try
            {
                int terminalId = int.Parse(lines[0]);
                List<record> tmpList = new List<record>();


                //更新记录
                for (int i = 1; i < lines.Length; ++i)
                {
                    if (lines[i].Trim().Length == 0)
                    {
                        continue;
                    }
                    string[] infos = lines[i].Split(',');
                    record record = new record();
                    record.terminalid = terminalId;
                    record.time = DateTime.Parse(infos[0]);
                    record.pointid = int.Parse(infos[1]);
                    record.h2s = float.Parse(infos[2]);
                    record.power = float.Parse(infos[3]);
                    //tmpList.Add(record);
                    //if (tmpList.Count() >= 1000)
                    //{
                    //    tmpList.Clear();
                    //    //using (h2sDataContext db = new h2sDataContext())
                    //    //{
                    //    //    db.record.InsertAllOnSubmit(tmpList);
                    //    //    db.SubmitChanges();
                    //    //}
                    //    //tmpList.Clear();
                    //}
                }
                //using (h2sDataContext db = new h2sDataContext())
                //{
                //    db.record.InsertAllOnSubmit(tmpList);
                //    db.SubmitChanges();
                //}
                //tmpList.Clear();

                using (h2sDataContext db = new h2sDataContext())
                {
                    //更新终端
                    var terminal = db.terminal.Where(p => p.id == terminalId).FirstOrDefault();
                    if (terminal == null)
                    {
                        terminal = new terminal();
                        terminal.id = terminalId;
                        terminal.lastImportTime = DateTime.Now;
                        db.terminal.InsertOnSubmit(terminal);
                    }
                    else
                    {
                        terminal.lastImportTime = DateTime.Now;
                    }
                    db.SubmitChanges();

                    //更新采集点列表
                    string sqlCmd = "insert into " +
                        "point " +
                        "select {0}, a.pointid, '' " +
                        "from record a " +
                        "where a.terminalid = {0} " +
                        "group by a.pointid " +
                        "having a.pointid not in (" +
                        "select " +
                        "a.pointid " +
                        "from point a " +
                        "where a.terminalid = {0})";
                    db.ExecuteCommand(sqlCmd, terminalId);
                }

                rtv = "ok";
            }
            catch (Exception e)
            {
                rtv = e.Message;
            }
            return rtv.ToHttpResponseMessage();
        }


        private HttpResponseMessage data_import (string dstPath)
        {
            string rtv = null;
            try
            {
                var rs = new StreamReader(File.OpenRead(dstPath));
                bool flag = true;
                int terminalId = -1;
                List<record> tmpList = new List<record>();
                while (rs.EndOfStream == false)
                {
                    string line = rs.ReadLine();
                    if (line.Trim().Length > 0)
                    {
                        if (flag)
                        {
                            terminalId = int.Parse(line);
                            flag = false;
                        }
                        else
                        {
                            string[] infos = line.Split(',');
                            record record = new record();
                            record.terminalid = terminalId;
                            record.time = DateTime.Parse(infos[0]);
                            record.pointid = int.Parse(infos[1]);
                            record.h2s = float.Parse(infos[2]);
                            record.power = float.Parse(infos[3]);
                            tmpList.Add(record);
                            if (tmpList.Count() >= 100000)
                            {
                                using (h2sDataContext db = new h2sDataContext())
                                {
                                    db.record.InsertAllOnSubmit(tmpList.ToArray());

                                    db.SubmitChanges();
                                }
                                tmpList.Clear();
                            }
                        }
                    }
                }
                using (h2sDataContext db = new h2sDataContext())
                {
                    db.record.InsertAllOnSubmit(tmpList.ToArray());
                    db.SubmitChanges();
                }
                tmpList.Clear();


                using (h2sDataContext db = new h2sDataContext())
                {
                    //更新终端
                    var terminal = db.terminal.Where(p => p.id == terminalId).FirstOrDefault();
                    if (terminal == null)
                    {
                        terminal = new terminal();
                        terminal.id = terminalId;
                        terminal.lastImportTime = DateTime.Now;
                        db.terminal.InsertOnSubmit(terminal);
                    }
                    else
                    {
                        terminal.lastImportTime = DateTime.Now;
                    }
                    db.SubmitChanges();

                    //更新采集点列表
                    string sqlCmd = "insert into " +
                        "point " +
                        "select {0}, a.pointid, '' " +
                        "from record a " +
                        "where a.terminalid = {0} " +
                        "group by a.pointid " +
                        "having a.pointid not in (" +
                        "select " +
                        "a.pointid " +
                        "from point a " +
                        "where a.terminalid = {0})";
                    db.ExecuteCommand(sqlCmd, terminalId);
                }

                rs.Close();
                rtv = "ok";
            }
            catch (Exception e)
            {
                rtv = e.Message;
            }
            return rtv.ToHttpResponseMessage();
        }

        [HttpGet, HttpPost]
        public HttpResponseMessage import ()
        {
            string rtv = null;
            try
            {
                var udisk = DriveInfo.GetDrives().Where(p => p.DriveType == DriveType.Removable).FirstOrDefault();
                if (udisk != null)
                {
                    string dstPath = udisk.RootDirectory + "export.txt";
                    if (File.Exists(dstPath))
                    {
                        return data_import(dstPath);
                    }
                    else
                    {
                        rtv = "未找到设备数据文件";
                        return rtv.ToHttpResponseMessage();
                    }
                }
                else
                {
                    rtv = "设备未插入笔记本";
                    return rtv.ToHttpResponseMessage();
                }
            }
            catch (Exception e)
            {
                rtv = e.Message;
                return rtv.ToHttpResponseMessage();
            }
        }
    }
}
